package com.ruoyi.electricity.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.electricity.domain.MultimediaUploadInfo;
import com.ruoyi.electricity.service.IMultimediaUploadInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片视频上传信息Controller
 *
 * @author ljw
 * @date 2023-12-17
 */
@RestController
@RequestMapping("/electricity/multimediaUploadInfo")
public class MultimediaUploadInfoController extends BaseController
{
    @Autowired
    private IMultimediaUploadInfoService multimediaUploadInfoService;

    @Value("${jy.local_ip}")
    private String JY_LOCALHOST_IP;

    /**
     * 查询图片视频上传信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(MultimediaUploadInfo multimediaUploadInfo, Date startTime, Date endTime)
    {
        startPage();
        List<MultimediaUploadInfo> list = multimediaUploadInfoService.selectMultimediaUploadInfoList(multimediaUploadInfo, startTime, endTime);
        return getDataTable(list);
    }



    /**
     * 获取图片视频上传信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(multimediaUploadInfoService.selectMultimediaUploadInfoById(id));
    }

    /**
     * 新增图片视频上传信息
     */
    @PostMapping
    public AjaxResult add(@Valid @ModelAttribute MultimediaUploadInfo multimediaUploadInfo)
    {

        if("192.168.14.27".equals(JY_LOCALHOST_IP)){
            JY_LOCALHOST_IP=JY_LOCALHOST_IP+":85";
        }

        MultipartFile file = multimediaUploadInfo.getFile();
        if (file.isEmpty()) {
            return error("请选择要上传的文件");
        }

        // 获取文件的原始名称
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        UUID uuid = UUID.randomUUID();
        String fileName = uuid.toString() + fileExtension;
        String storagePath = "";

        if (isImage(fileName)) {
            storagePath = "D:/zdzh/var/image/";
            multimediaUploadInfo.setMultimediaType("图片");
            multimediaUploadInfo.setMultimediaUrl("http://"+JY_LOCALHOST_IP+"/zdzh/var/image/"+fileName);
        } else if (isVideo(fileName)) {
            storagePath = "D:/zdzh/var/video/";
            multimediaUploadInfo.setMultimediaType("视频");
            multimediaUploadInfo.setMultimediaUrl("http://"+JY_LOCALHOST_IP+"/zdzh/var/video/"+fileName);
        }else {
            return error("请上传正确格式的文件，仅接收图片或视频文件");
        }

        try {
            // 创建目标文件对象
            File destFile = new File(storagePath + fileName);
            // 检查目标目录是否存在，不存在则创建
            File destDirectory = destFile.getParentFile();
            if (!destDirectory.exists()) {
                destDirectory.mkdirs();
            }
            // 将文件保存到目标位置
            FileOutputStream fos = new FileOutputStream(destFile);
            fos.write(file.getBytes());
            fos.close();
            multimediaUploadInfoService.insertMultimediaUploadInfo(multimediaUploadInfo);
            return success("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return error("文件上传失败");
        }
    }



    /**
     * 修改图片视频上传信息
     */
    @PutMapping
    public AjaxResult edit(@RequestBody MultimediaUploadInfo multimediaUploadInfo)
    {
        return toAjax(multimediaUploadInfoService.updateMultimediaUploadInfo(multimediaUploadInfo));
    }

    /**
     * 删除图片视频上传信息
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(multimediaUploadInfoService.deleteMultimediaUploadInfoByIds(ids));
    }



    private  boolean isImage(String fileName) {
        String extension = getExtension(fileName);
        if (StringUtils.isEmpty(extension)) {
            return false;
        }
        switch (extension.toLowerCase()) {
            case "jpg":
            case "jpeg":
            case "png":
            case "gif":
            case "bmp":
            case "tiff":
            case "webp":
            case "ico":
            case "heif":
            case "jfif":
            case "psd":
            case "nef":
            case "cr2":
            case "arw":
            case "orf":
            case "erf":
                return true;
            default:
                return false;
        }
    }
    private  boolean isVideo(String fileName) {
        String extension = getExtension(fileName);
        if (StringUtils.isEmpty(extension)) {
            return false;
        }
        switch (extension.toLowerCase()) {
            case "mp4":
            case "avi":
            case "mov":
            case "flv":
            case "wmv":
            case "mkv":
            case "vob":
            case "dvr-ms":
            case "asf":
            case "qt":
                return true;
            default:
                return false;
        }
    }
    private  String getExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1) {
            return "";
        }
        return fileName.substring(dotIndex + 1);
    }
}
